package com.i_art_engineer.meigong.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.FullScreenActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import cz.msebera.android.httpclient.Header;

/**
 * 登录界面
 */
public class LoginActivity extends FullScreenActivity {

    private TextView tv_resetpwd, tv_register, tv_login;
    private EditText et_mobile, et_pwd;
    private CheckBox checkBox_jizhu;
    private SharedPreferences preferences = AppContext.getPersistPreferences();

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            switch (arg0.getId()) {

                case R.id.tv_register:
                    LoginActivity.this.startActivityForResult(new Intent(LoginActivity.this, RegisterActivity.class), 1);
                    break;
                case R.id.tv_resetpwd:
                    LoginActivity.this.startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                    break;
                case R.id.tv_login:

                    final String mobile = et_mobile.getText().toString();
                    final String pwd = et_pwd.getText().toString();

                    if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(pwd)) {
                        Toast.makeText(LoginActivity.this, "账号或者密码不能为空！", Toast.LENGTH_SHORT).show();
                        break;
                    }

                    RequestParams params = new RequestParams();
                    params.add("phone", mobile);
                    params.add("pwd", pwd);
                    params.add("os", "android");
                    JsonHttpResponseHandler jhandler = new JsonHttpResponseHandler() {

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            Log.i("loginonSuccess", response.toString());
                            try {
                                int code = response.getInt("code");
                                String msg = response.getString("msg");
                                if (code == 200) {
                                    JSONObject data = response.getJSONObject("data");
                                    String token = data.getString("ticket");
                                    AppContext.setTicket(token);
                                    Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                                    if (checkBox_jizhu.isChecked()) {
                                        String username = new String(Base64.encode(mobile.getBytes(), Base64.URL_SAFE));
                                        String userpwd = new String(Base64.encode(pwd.getBytes(), Base64.URL_SAFE));
                                        preferences.edit().putString("username", username).putString("userpwd", userpwd).putBoolean("userjizhu", true).commit();
                                    }
                                    LoginActivity.this.startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                } else {
                                    Toast.makeText(LoginActivity.this, "登陆失败！" + msg, Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                            super.onFailure(statusCode, headers, throwable, errorResponse);
                            Toast.makeText(LoginActivity.this,"连接服务器超时",Toast.LENGTH_SHORT).show();
//                            Log.e("loginonFailure", errorResponse.toString());
//                            Log.e("loginonFailure", throwable.toString());
                        }
                    };
                    AppHttpClient.post(AppConsts.API_ACCOUNT_LOGIN, params, jhandler);

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        tv_register = (TextView) findViewById(R.id.tv_register);
        tv_resetpwd = (TextView) findViewById(R.id.tv_resetpwd);
        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_register.setOnClickListener(listener);
        tv_resetpwd.setOnClickListener(listener);
        tv_login.setOnClickListener(listener);

        checkBox_jizhu = (CheckBox) findViewById(R.id.checkBox);

        et_mobile = (EditText) findViewById(R.id.tv_mobile);
        et_pwd = (EditText) findViewById(R.id.tv_password);

        String username = preferences.getString("username", "");
        String userpwd = preferences.getString("userpwd", "");
        boolean userjizhu = preferences.getBoolean("userjizhu", false);

        // 记住密码
        if (userjizhu) {
            username = new String(Base64.decode(username, Base64.URL_SAFE));
            userpwd = new String(Base64.decode(userpwd, Base64.URL_SAFE));

            if (!TextUtils.isEmpty(username)) {
                et_mobile.setText(username);
            }
            if (!TextUtils.isEmpty(userpwd)) {
                et_pwd.setText(userpwd);
            }
            checkBox_jizhu.setChecked(true);
        }

        checkBox_jizhu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    String mobile = et_mobile.getText().toString();
                    String pwd = et_mobile.getText().toString();
                    if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(pwd)) {
                        Toast.makeText(LoginActivity.this, "账号或者密码不能为空！", Toast.LENGTH_SHORT).show();
                    } else {
                        mobile = new String(Base64.encode(mobile.getBytes(), Base64.URL_SAFE));
                        pwd = new String(Base64.encode(pwd.getBytes(), Base64.URL_SAFE));
                        preferences.edit().putString("username", mobile).putString("userpwd", pwd).putBoolean("userjizhu", true).commit();
                    }

                } else {
                    preferences.edit().remove("username").remove("userpwd").putBoolean("userjizhu", false).commit();
                }

                checkToken();
            }
        });
    }

    private void checkToken() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            //说明来自注册
            if (resultCode == 1) {
                Log.i("activityresult", "注册成功");
                String username = preferences.getString("username", "");
                String userpwd = preferences.getString("userpwd", "");
                username = new String(Base64.decode(username, Base64.URL_SAFE));
                userpwd = new String(Base64.decode(userpwd, Base64.URL_SAFE));
                et_mobile.setText(username);
                et_pwd.setText(userpwd);

            } else {
                Log.i("activityresult", "注册失败");
            }
        } else if (requestCode == 2) {
            //说明来自修改密码
            et_pwd.setText(null);
            checkBox_jizhu.setChecked(false);
        }
    }

}
